<template>
  <!-- 利用 el-table 模拟微博动态展示，保留原有数据请求逻辑 -->
  <el-table :data="tableData" stripe style="width: 100%" border >
    <!-- 自定义一列，用来渲染类似微博动态的内容 -->
    <el-table-column label="博客动态" align="center">
      <template #default="scope">
        <div class="weibo-card">
          <!-- 头像及发布者信息区域 -->
          <div class="weibo-card__header">
            <!-- 这里假设数据里有头像字段 avatar，可根据实际接口返回调整 -->
            <img :src="'/img'+user.tx"  class="weibo-card__avatar" />
            <div class="weibo-card__info">
              <!-- 发布者名称，对应原 userId 字段，可根据实际改 -->
              <span class="weibo-card__nickname">{{ user.nc }}</span>
              <span class="weibo-card__meta">
                <!-- 发布时间，对应原 time 字段 -->
                {{ scope.row.time }}
                <!-- 发布来源，可根据实际接口返回决定是否显示及字段 -->
                来自 博客网页版
                <button @click="handleRowClick(scope.row)" style="border: none;color: black">查看详细</button>
                <!-- 只有当前用户的帖子才显示删除按钮 -->
                <button
                    @click="showDeleteConfirm(scope.row)"
                    style="border: none;color: #ff4d4f;margin-left: 10px"
                    v-if="scope.row.userId === myId"
                >
                  删除
                </button>
              </span>
              <div class="weibo-card__meta">
                标题# {{ scope.row.title }}
              </div>
            </div>
          </div>
          <!-- 动态内容区域，对应原 text 字段 -->
          <div class="weibo-card__content">
            {{ scope.row.text }}
            <!-- 假设数据里有图片字段 images，可循环展示图片，这里简单模拟单图 -->
            <div class="weibo-card__image" v-if="scope.row.url && scope.row.url.trim()">
              <img
                  v-for="(imgUrl, index) in scope.row.url.split(',')"
                  :key="index"
                  :src="'/img'+imgUrl.trim()"
                  class="imgs"
              />
            </div>
          </div>
          <div class="weibo-card__actions">
            <span class="weibo-card__action">
              <el-icon class="el-icon"><ChatDotRound /></el-icon>
              {{ scope.row.commentCount || 0 }}
            </span>

            <!-- 点赞按钮（带状态） -->
            <span class="weibo-card__action" >
              <el-icon class="el-icon" :class="{ 'liked': scope.row.isLiked }"><Pointer /></el-icon>
              {{ scope.row.likeCount || 0 }}
            </span>

            <!-- 收藏按钮（带状态） -->
            <span class="weibo-card__action" >
              <el-icon class="el-icon" :class="{ 'collected': scope.row.isCollected }"><StarFilled /></el-icon>
              {{ scope.row.collectCount || 0 }}
            </span>

            <span class="weibo-card__action">
              <el-icon class="el-icon"><View /></el-icon>
              {{ scope.row.browse || 0 }}
            </span>
          </div>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <!-- 删除确认对话框 -->
  <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%" >
    <p>您确定要删除这条动态吗？此操作不可撤销。</p>
    <template #footer>
      <el-button @click="deleteDialogVisible = false">取消</el-button>
      <el-button type="danger" @click="confirmDelete">确定删除</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios';
import {ref, onMounted, defineExpose} from 'vue';
import router from "../router";
import {useUserStore} from '@/stores/user'
import {useRoute} from "vue-router";
const userStore = useUserStore()
const myId= ref(userStore.id)
// 引入 Element Plus 图标
import { ChatDotRound, StarFilled, View, Pointer } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const userId = ref();
const user = ref({
  id: '',
  nc: '',
  drb: '',
  url: '',
  tx: '',
});

// 删除相关的状态
const deleteDialogVisible = ref(false);
const postToDelete = ref(null);

const handleRowClick = (row) => {
  router.push(`/poster?id=${row.id}`);
};

const post = ref({
  id: '',
  userId: '',
  time: '',
  text: '',
  url: '',
  avatar: '/src/assets/', // 默认头像示例
  commentCount: 0,
  likeCount: 0,
  forwardCount: 0,
});

const tableData = ref([]);

const handleUpdateData = async (obj) => {
  user.value = obj;
  post.value.userId = user.value.id;
  await doPostList();
};

const doPostList = async () => {
  const { data } = await axios.get('/api/postUser/YW/' + user.value.id);
  tableData.value = data;

  for (const item of tableData.value) {
    item.likeCount = await getNcByUserId(item.id);
    item.collectCount = await getTxByUserId(item.id);
    item.commentCount = await getCommentCount(item.id);
  }
};

const getNcByUserId = async (id) => {
  const { data } = await axios.get('/api/likes/' + id);
  return data;
};

const getTxByUserId = async (id) => {
  const { data } = await axios.get('/api/collect/count/post/' + id);
  return data;
};

const getCommentCount = async (id) => {
  const { data } = await axios.get('/api/commentp/withReplies/' + id);
  return data.length;
};

// 显示删除确认对话框
const showDeleteConfirm = (row) => {
  postToDelete.value = row;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!postToDelete.value) return;

  try {
    // 发送删除请求到后端
    await axios.delete(`/api/post/${postToDelete.value.id}`);

    // 显示成功消息
    ElMessage.success('帖子删除成功');

    // 关闭对话框
    deleteDialogVisible.value = false;

    // 重新加载数据
    await doPostList();
  } catch (error) {
    console.error('删除帖子失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
};

onMounted(async () => {
  await doPostList();
});

defineExpose({
  handleUpdateData,
});
</script>

<style scoped>
.weibo-card {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.weibo-card__header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.weibo-card__avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
}
.weibo-card__info {
  display: flex;
  flex-direction: column;
}
.weibo-card__nickname {
  font-weight: bold;
  color: #333;
}
.weibo-card__meta {
  font-size: 12px;
  color: #999;
}
.weibo-card__content {
  margin: 8px 0;
  color: #333;
  line-height: 1.6;
}
.weibo-card__image {
  margin-top: 8px;
}
.weibo-card__image img {
  max-width: 200px;
  border-radius: 4px;
}
.weibo-card__actions {
  display: flex;
  gap: 24px;
  color: #666;
  margin-top: 8px;
  cursor: pointer;
}
.weibo-card__action {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
}
.weibo-card__action:hover {
  color: #409eff;
}
.imgs{
  width: 133px;
  height: 133px;
  margin:0 2px;
}
.liked {
  color: #ff4d4f;
}
.collected {
  color: #faad14;
}
</style>
